import HttpClient from '../commons/http-client';
import {updateConstant} from '../reducers/constant';
import _ from 'lodash';
import AsyncStorage from '@react-native-async-storage/async-storage';

export function loadCountry() {
  return async dispatch => {
    const countryRep = await HttpClient.get('/web/country?no_page=no_page');
    dispatch(updateConstant({country: countryRep.data.data}));
  };
}

export function loadCategory() {
  return async dispatch => {
    let category = await AsyncStorage.getItem('@category');
    if (category) {
      dispatch(updateConstant({category: JSON.parse(category)}));
    }
    const categoryRep = await HttpClient.get('/web/category/a');
    category = _.get(categoryRep, 'data.data', null);
    if (category) {
      dispatch(updateConstant({category}));
      await AsyncStorage.setItem('@category', JSON.stringify(category));
    }

    let selections = await AsyncStorage.getItem('@selections');
    if (selections) {
      dispatch(updateConstant({selections: JSON.parse(selections)}));
    }
    const selectionsRep = await HttpClient.get('/web/dent/order-selection');
    selections = _.get(selectionsRep, 'data.data.results', null);
    if (selections) {
      dispatch(updateConstant({selections}));
      await AsyncStorage.setItem('@selections', JSON.stringify(selections));
    }
  };
}
